<?php

namespace app\common\model\banxi\learn;

use app\common\model\common\BaseModel;
use app\common\service\TextToSpeechService;
use app\common\service\TranslateService;
use think\facade\Log;
use think\model\concern\SoftDelete;

/**
 * 学习-阅读理解标记词库
 */
class LearnReadingArticleMarkWord extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_learn_reading_article_mark_word';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [

    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'studentId' => 'string',
        'readingArticleId' => 'string',
        'courseId' => 'string',
        'articleId' => 'string',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];


    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------


    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //-----------------------------------------------------------------------------------

    /*
     * 获取阅读理解标记词库
     * */
    public function getByReadingArticleId(array|object $readingArticle): array|object
    {
        $learnMeans = $readingArticle['learnMeans'];
        $studentId = $readingArticle['studentId'];
        $readingArticleId = $readingArticle['id'];
        $where = [];
        if ($studentId) {
            $where[] = ['studentId', '=', $studentId];
        }
        if ($readingArticle['readingType'] == 1) {
            $where[] = ['readingArticleId', '=', $readingArticleId];
        } elseif ($readingArticle['readingType'] == 2) {
            if ($learnMeans == 1) {
                $where[] = ['articleId', '=', $readingArticle['articleId']];
            } else {
                $where[] = ['readingArticleId', '=', $readingArticleId];
            }
        } else {
            getResponseException('系统错误', [], 1, 'ERROR');
        }

        $list = $this->where($where)->select();
        return $list;
    }

    /*
     *加入生词
     * @param $readingArticleId
     * @param $word
     * @param $trainerId
     * @param $studentId
     * */
    public function markWord(int $readingArticleId, string $word, int|null $trainerId, int|null $studentId): bool
    {
        $LearnReadingArticleModel = new LearnReadingArticle();
        $readingInfo = $LearnReadingArticleModel
            ->where(['id' => $readingArticleId])
            ->find();
        if (!$readingInfo) {

        }
        if (!$trainerId) {
            if ($readingInfo['trainerId'] == $trainerId) {
                getResponseException('阅读记录不存在', [], 1, 'ERROR');
            }
        }
        if (!$studentId) {
            if ($readingInfo['studentId'] == $studentId) {
                getResponseException('阅读记录不存在', [], 1, 'ERROR');
            }
        }
        //处理加入生词本逻辑
        $this->createByReadingArticleAndWord($readingInfo, $word);
        return true;
    }

    /*
     * 创建阅读文章生词
     * @param $readingInfo
     * @param $word
     * @param $trainerId
     * @param $studentId
     * */
    public function createByReadingArticleAndWord(array|object $readingInfo, string $word): bool
    {
        $learnMeans = $readingInfo['learnMeans'];
        $studentId = $readingInfo['studentId'];
        $readingArticleId = $readingInfo['id'];
        $courseId = explode(',', $readingInfo['actualCourseId'])[0];

        try {
            if ($studentId) {
                $lockKey = "LearnReadingArticleMarkWord:add:" . $studentId;
                // 尝试设置缓存锁，有效期3秒
                if (!cache()->has($lockKey)) {
                    // 设置锁并保持3秒
                    cache()->set($lockKey, 1, 3);
                } else {
                    // 如果已经存在锁，则抛出异常
                    getResponseException('操作太频繁啦,请稍后重试', [], 1, 'ERROR');
                }
            }
            $where = [];
            $where[] = ['studentId', '=', $studentId];
            $where[] = ['word', '=', $word];
            if ($readingInfo['readingType'] == 1) {
                $where[] = ['readingArticleId', '=', $readingArticleId];
            } elseif ($readingInfo['readingType'] == 2) {
                if ($learnMeans == 1) {
                    $where[] = ['articleId', '=', $readingInfo['articleId']];
                } else {
                    $where[] = ['readingArticleId', '=', $readingArticleId];
                }
                $where[] = ['courseId', '=', $courseId];
            } else {
                getResponseException('系统错误', [], 1, 'ERROR');
            }

            $readingArticleMarkWord = $this->where($where)->find();

            if (!$readingArticleMarkWord) {
                //有道文本翻译（英-中）
                $TranslateService = new TranslateService();
                $translate_result = $TranslateService->textTranslation($word);
                Log::info('有道文本翻译:{translate_result}', ['translate_result' => json_encode($translate_result, JSON_UNESCAPED_UNICODE)]);
                if ($translate_result['errorCode'] != 0) {
                    getResponseException('翻译错误：' . $translate_result['errorCode'], [], 1, 'ERROR');
                }
                //生成单词音频
                $TextToSpeech = new TextToSpeechService();
                $audio_url = $TextToSpeech->create_request($word, 'youmeimei');
                Log::info('生成单词音频:' . $audio_url);
                if (!$audio_url) {
                    $this->error('句子语音生成失败');
                }
                //组装写入数据
                $insert_data['studentId'] = $studentId;
                $insert_data['word'] = $word;
                $insert_data['readingArticleId'] = $readingArticleId;
                if ($readingInfo['readingType'] == 2) {
                    $insert_data['courseId'] = $courseId;
                    $insert_data['articleId'] = $readingInfo['articleId'];
                }
                $insert_data['firstLetter'] = $insert_data['firstLetter'] = mb_substr($word, 0, 1, 'UTF-8');

                $insert_data['wordAudio'] = $audio_url;
                $insert_data['translation'] = $translate_result['translation'][0];
                Log::info('新增生词参数:{insert_data}', ['insert_data' => json_encode($insert_data, JSON_UNESCAPED_UNICODE)]);
                $this->save($insert_data);
            }
            //
        } catch (\Exception $e) {
            getResponseException('系统错误:' . $e->getMessage(), [], 1, 'ERROR');
        }
        return true;
    }

    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------


}